package com.hue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hue.entity.EduChapter;
import com.hue.entity.EduVideo;
import com.hue.entity.vo.ChapterVo;
import com.hue.entity.vo.VideoVo;
import com.hue.mapper.EduChapterMapper;
import com.hue.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hue.service.EduVideoService;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 姚凤桥
 * @since 2021-06-13
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService eduVideoService;

    //根据courseId查询所有chapter
    @Override
    public List<ChapterVo> findByCourseId(String courseId) {
        List<ChapterVo> chapterVos = new ArrayList<>();
        Map<String, ChapterVo> map = new HashedMap<>();
        //根据courseId查询所有chapter
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        List<EduChapter> eduChapters = list(wrapper);
        for (EduChapter eduChapter : eduChapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            map.put(eduChapter.getId(),chapterVo);
        }
        //根据courseId查询所有video
        QueryWrapper<EduVideo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("course_id",courseId);
        List<EduVideo> eduVideos = eduVideoService.list(wrapper1);
        //将eduVideos放到对应的chapterVos中
        for(EduVideo eduVideo:eduVideos){
            if(map.containsKey(eduVideo.getChapterId())){
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(eduVideo,videoVo);
                map.get(eduVideo.getChapterId()).addVideo(videoVo);
            }
        }
        //将map中的数据放入到chapterVos中
        for(String key:map.keySet()){
            chapterVos.add(map.get(key));
        }
        return chapterVos;
    }

    @Override
    public boolean deleteById(String id) {
        //判断章节下面是否有小节
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id", id);
        int count = eduVideoService.count(wrapper);
        if(count > 0){  //有小节
            return false;
        }
        //删除章节
        return removeById(id);
    }
}
